#!/home/he/anaconda3/envs/hellobot/bin/python
# -*- encoding:utf-8 -*-

# import hashlib
# import hmac
# import base64
# from socket import *
# import json, time, threading
# from websocket import create_connection
# import websocket
# from urllib.parse import quote
# import logging
# import pyaudio
# import re

# # reload(sys)
# # sys.setdefaultencoding("utf8")

# CHUNK = 1280  # 定义数据流块
# FORMAT = pyaudio.paInt16  # 量化位数（音量级划分）
# CHANNELS = 1  # 声道数;
# RATE = 16000  # 采样率;Hz
# app_id = "7dec9556"
# api_key = "07e5167cd501ff6c1a0061f5f9e7b685"
# loop = True


# class Client:
#     def __init__(self):
#         base_url = "ws://rtasr.xfyun.cn/v1/ws"
#         ts = str(int(time.time()))
#         tt = (app_id + ts).encode('utf-8')
#         md5 = hashlib.md5()
#         md5.update(tt)
#         baseString = md5.hexdigest()
#         baseString = bytes(baseString, encoding='utf-8')
#         punc = "0"

#         apiKey = api_key.encode('utf-8')
#         signa = hmac.new(apiKey, baseString, hashlib.sha1).digest()
#         signa = base64.b64encode(signa)
#         signa = str(signa, 'utf-8')
#         self.end_tag = "{\"end\": true}"

#         self.ws = create_connection(base_url + "?appid=" + app_id + "&ts=" + ts + "&punc=" + punc + "&signa=" + quote(signa))
#         self.trecv = threading.Thread(target=self.recv)
#         self.trecv.start()

#     def send(self):
#         try:
#             p = pyaudio.PyAudio()
#             stream = p.open(format=FORMAT,
#                             channels=CHANNELS,
#                             rate=RATE,
#                             input=True,
#                             frames_per_buffer=CHUNK)
#             print("*" * 10, "请输入语音指令")
#             while loop:
#                 data = stream.read(CHUNK)
#                 self.ws.send(data)
#                 time.sleep(0.04)
#         finally:
#             print("*" * 10, "语音指令输入结束")
#             stream.stop_stream()
#             stream.close()  # 关闭
#             p.terminate()  # 终结

#         self.ws.send(bytes(self.end_tag.encode('utf-8')))
#         print("send end tag success")

#     def recv(self):
#         try:
#             while self.ws.connected:
#                 signal = "0"
#                 result = str(self.ws.recv())
#                 if len(result) == 0:
#                     print("receive result end")
#                     break
#                 result_dict = json.loads(result)
#                 # 解析结果
#                 if result_dict["action"] == "started":
#                     print("handshake success, result: " + result)

#                 if result_dict["action"] == "result":
#                     result_1 = json.loads(result_dict["data"])
#                     result_2 = result_1["cn"]["st"]["rt"][0]["ws"]
#                     word = ""
#                     for per_result in result_2:
#                         word = word + str(per_result["cw"][0]["w"])
                    #   searchObj1 = re.search("前", word)
                    #   searchObj2 = re.search("后", word)
                    #   searchObj3 = re.search("左", word)
                    #   searchObj4 = re.search("右", word)
                    #   searchObj5 = re.search("停", word)
                    #   if searchObj1 != None:
                    #       signal = "w"
                    #   if searchObj2 != None:
                    #       signal = "s"
                    #   if searchObj3 != None:
                    #       signal = "a"
                    #   if searchObj4 != None:
                    #       signal = "d"
                    #   if searchObj5 != None:
                    #       stop_listen()
#                     #todo 发指令接口
#                     print("rtasr result: " + word)
#                     print("signal:" + signal)

#                 if result_dict["action"] == "error":
#                     print("rtasr error: " + result)
#                     self.ws.close()
#                     return
#         except websocket.WebSocketConnectionClosedException:
#             print("receive result end")

#     def close(self):
#         self.ws.close()
#         print("connection closed")


# def start_listen():
#     logging.basicConfig()

#     client = Client()
#     client.send()


# def stop_listen():
#     global loop
#     loop = False


# if __name__ == '__main__':
#     start_listen()


import hashlib
import hmac
import base64
from socket import *
import json, time, threading
from websocket import create_connection
import websocket
from urllib.parse import quote
import logging
import pyaudio
import re

import rospy
import numpy as np
from hellobot_msgs.msg import msg_call
from std_msgs.msg import String

# reload(sys)
# sys.setdefaultencoding("utf8")

CHUNK = 1280  # 定义数据流块
FORMAT = pyaudio.paInt16  # 量化位数（音量级划分）
CHANNELS = 1  # 声道数;
RATE = 16000  # 采样率;Hz
app_id = "7dec9556"
api_key = "07e5167cd501ff6c1a0061f5f9e7b685"
loop = True


class Client:
    def __init__(self):

        self.pub = rospy.Publisher('VoiceCommand', String, queue_size=10)
        rate = rospy.Rate(10)

        base_url = "ws://rtasr.xfyun.cn/v1/ws"
        ts = str(int(time.time()))
        tt = (app_id + ts).encode('utf-8')
        md5 = hashlib.md5()
        md5.update(tt)
        baseString = md5.hexdigest()
        baseString = bytes(baseString, encoding='utf-8')
        punc = "0"

        apiKey = api_key.encode('utf-8')
        signa = hmac.new(apiKey, baseString, hashlib.sha1).digest()
        signa = base64.b64encode(signa)
        signa = str(signa, 'utf-8')
        self.end_tag = "{\"end\": true}"

        self.ws = create_connection(base_url + "?appid=" + app_id + "&ts=" + ts + "&punc=" + punc + "&signa=" + quote(signa))
        self.trecv = threading.Thread(target=self.recv)
        self.trecv.start()

    def send(self):
        try:
            p = pyaudio.PyAudio()
            stream = p.open(format=FORMAT,
                            channels=CHANNELS,
                            rate=RATE,
                            input=True,
                            frames_per_buffer=CHUNK)
            print("*" * 10, "请输入语音指令")
            while loop:
                data = stream.read(CHUNK)
                self.ws.send(data)
                time.sleep(0.04)
        finally:
            print("*" * 10, "语音指令输入结束")
            stream.stop_stream()
            stream.close()  # 关闭
            p.terminate()  # 终结

        self.ws.send(bytes(self.end_tag.encode('utf-8')))
        print("send end tag success")

    def recv(self):
        try:
            while self.ws.connected:
                signal = "0"
                result = str(self.ws.recv())
                if len(result) == 0:
                    print("receive result end")
                    break
                result_dict = json.loads(result)
                # # 解析结果
                # if result_dict["action"] == "started":
                #     print("handshake success, result: " + result)

                # if result_dict["action"] == "result":
                #     result_1 = json.loads(result_dict["data"])
                #     result_2 = result_1["cn"]["st"]["rt"][0]["ws"]
                #     word = ""
                #     for per_result in result_2:
                #         word = word + str(per_result["cw"][0]["w"])
                #     if word == u'前进':
                #         signal = "w"
                #     if word == u'后退':
                #         signal = "s"
                #     if word == u'左转':
                #         signal = "a"
                #     if word == u'右转':
                #         signal = "d"
                #     if word == u"停止":
                #         stop_listen()
                # 解析结果
                if result_dict["action"] == "started":
                    print("handshake success, result: " + result)

                if result_dict["action"] == "result":
                    result_1 = json.loads(result_dict["data"])
                    result_2 = result_1["cn"]["st"]["rt"][0]["ws"]
                    word = ""
                    for per_result in result_2:
                        word = word + str(per_result["cw"][0]["w"])
                        searchObj1 = re.search("前", word)
                        searchObj2 = re.search("后", word)
                        searchObj3 = re.search("左", word)
                        searchObj4 = re.search("右", word)
                        searchObj5 = re.search("停", word)
                        if searchObj1 != None:
                            signal = "w"
                        if searchObj2 != None:
                            signal = "s"
                        if searchObj3 != None:
                            signal = "a"
                        if searchObj4 != None:
                            signal = "d"
                        if searchObj5 != None:
                            stop_listen()
                    #todo 发指令接口
                    # self.pubmsg()
                    self.pub.publish(signal)
                    rospy.loginfo(signal)
                    print("rtasr result: " + word)
                    print("signal:" + signal)
                
                time.sleep(0.04)

                if result_dict["action"] == "error":
                    print("rtasr error: " + result)
                    self.ws.close()
                    return
        except websocket.WebSocketConnectionClosedException:
            print("receive result end")

    def close(self):
        self.ws.close()
        print("connection closed")

    # def pubmsg(self, signal):
    #     msg = signal
    #     new, target = Aim()
    #     msg.newstatus = new
    #     msg.x = target[0]
    #     msg.y = target[1]
    #     msg.z = target[2]

    #     self.pub.publish(msg)
    #     rospy.loginfo(msg)

def start_listen():
    logging.basicConfig()

    client = Client()
    client.send()


def stop_listen():
    global loop
    loop = False


if __name__ == '__main__':
    rospy.init_node('VoiceControl')
    try:
        start_listen()
    except rospy.ROSInterruptException:
        pass
    rospy.spin()
